import request, {BusinessException, TokenException} from "../request"
// import RCTDeviceEventEmitter from 'RCTDeviceEventEmitter'
import EventEmitter from "../src/common/EventEmitter.js"
import {identityhost} from "../app_config.js"
import { SLOTH_TOKEN } from "../const"

export const TokenChangedEvent = "token_change"
export const UserChangedEvent = "user_change"

export let VerifyPhone = async function (phone) {
    let json = await request({
        headerHost: identityhost,
        url: '/api/account/VerifyPhone',
        params: {
            phonenumber: phone
        }
    })
    console.log('VerifyPhone:' + JSON.stringify(json))
    return json
}

async function UpdateUser() {
    let user = await request({
        headerHost: identityhost,
        url: '/api/user',
        type: "GET"
    })
    if (!user || !user.phoneNumber) throw Error()
    const valuestring = await localStorage.getItem(SLOTH_TOKEN)
    var value = JSON.parse(valuestring)
    value.user = user
    await localStorage.setItem(SLOTH_TOKEN, JSON.stringify(value))
    EventEmitter.emit(UserChangedEvent, "")
    // todo:RCTDeviceEventEmitter.emit(UserChangedEvent, "")
}

export let LoginByPassword = async function (username, password) {
    let json = await request({
        headerHost: identityhost,
        url: '/api/account/login',
        type: "POST",
        params: {
            userName: username,
            password: password
        }
    })
    if (!json.accessToken || !json.user) throw Error()
    await localStorage.setItem(SLOTH_TOKEN, JSON.stringify(json))
    EventEmitter.emit(TokenChangedEvent, json.accessToken)
    // todo: RCTDeviceEventEmitter.emit(TokenChangedEvent, json.accessToken)
}

// export const Scene = {
//     Register: 1,
//     Login: 2,
//     SetPassword: 3,
//     ForgetPassword: 4,
//     ChangePassword: 5
// }

export let SendCode = async function (id) {
    /*
    * result:
    * {
    *   result:true/false,
    *   throttle:{
    *     perSecond: 60,
    *   }
    * }
    * */
    let json = await request({
        headerHost: identityhost,
        url: '/api/account/sendcode',
        type: "POST",
        params: {
            phonenumber: id
        }
    })
    return json
}

export let Register = async function(phone, code) {
    let json = await request({
        headerHost: identityhost,
        url: '/api/account/register',
        type: "POST",
        params: {
            phonenumber: phone,
            code: code
        }
    })
    if (!json.accessToken || !json.user) throw Error()
    await localStorage.setItem(SLOTH_TOKEN, JSON.stringify(json))
    EventEmitter.emit(TokenChangedEvent, json.accessToken)
    // todo: RCTDeviceEventEmitter.emit(TokenChangedEvent, json.accessToken)
}

export let LoginByCode = async function(phone, code) {
    let json = await request({
        headerHost: identityhost,
        url: '/api/account/verifycode',
        type: "POST",
        params: {
            phonenumber: phone,
            code: code
        }
    })
    if (!json.accessToken || !json.user) throw Error()
    await localStorage.setItem(SLOTH_TOKEN, JSON.stringify(json))
    EventEmitter.emit(TokenChangedEvent, json.accessToken)
    // todo: RCTDeviceEventEmitter.emit(TokenChangedEvent, json.accessToken)
}

export let SetPassword = async function (code, password) {
    let user = await CurrentUser()
    let json = await request({
        headerHost: identityhost,
        url: '/api/account/resetpassword',
        type: "POST",
        params: {
            phoneNumber: user.phonenumber,
            password: password,
            code: code
        }
    })
    if (!json.accessToken || !json.user) throw Error()
    await UpdateUser()
}

export let SetNickname = async function (nickname) {
    let json = await request({
        headerHost: identityhost,
        url: '/api/user/',
        type: "PUT",
        params: {
            nickname: nickname
        }
    })
    if (!json.accessToken || !json.user) throw Error()
    await UpdateUser()
}

export let SetAvatarUrl = async function(url){
    let json = await request({
        headerHost: identityhost,
        url: '/api/user/',
        type: "PUT",
        params: {
            avatarUrl:url
        }
    })
    if (!json.accessToken || !json.user) throw Error()
    await UpdateUser()
}

export let LoginOut = async function () {
    await localStorage.removeItem(SLOTH_TOKEN)
    EventEmitter.emit(TokenChangedEvent, "")
    // todo: RCTDeviceEventEmitter.emit(TokenChangedEvent, "")
}
EventEmitter.addListener("request_logout", LoginOut)
// todo: RCTDeviceEventEmitter.addListener("request_logout", LoginOut)

export let CurrentUser = async function () {
    const value = await localStorage.getItem(SLOTH_TOKEN)
    try {
        var token = JSON.parse(value)
        if (token.user) return token.user
    } catch (e) {
        await localStorage.removeItem(SLOTH_TOKEN)
    }
    throw new TokenException()
}
